import React, { useRef, useState } from 'react';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  Button,
  message,
  Upload,
  Modal,
  Form,
  Input,
  InputNumber,
  Space,
  Popconfirm,
} from 'antd';
import type { UploadProps } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { 
  qryTopBannerListPage,
  addTopBannerPic,
  updateTopBannerPic,
  deleteTopBannerPic
} from '@/services/banner';

// 定义轮播图数据类型
interface BannerItem {
  bannerId: string;
  serNum: number;
  picUrl: string;
}

// 定义请求返回的数据结构
interface RequestData {
  data: BannerItem[];
  success: boolean;
  total: number;
}

import { uploadMinio } from '@/services/common';

const BannerPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增轮播图');
  const [currentBanner, setCurrentBanner] = useState<BannerItem | null>(null);
  const [imageUrl, setImageUrl] = useState<string>('');
  const [confirmLoading, setConfirmLoading] = useState(false);

  // 表格列定义
  const columns: ProColumns<BannerItem>[] = [
    {
      title: '排序序号',
      dataIndex: 'serNum',
      sorter: true,
      width: 120,
    },
    {
      title: '轮播图ID',
      dataIndex: 'bannerId',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '图片预览',
      dataIndex: 'picUrl',
      search: false,
      render: (_, record) => (
        <img 
          src={record.picUrl} 
          alt="轮播图" 
          style={{ width: '100px', height: '60px', objectFit: 'cover' }} 
        />
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <Button 
          key="edit" 
          type="link" 
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个轮播图吗?"
          onConfirm={() => handleDelete(record.bannerId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  // 处理编辑
  const handleEdit = (record: BannerItem) => {
    setCurrentBanner(record);
    setImageUrl(record.picUrl);
    form.setFieldsValue({
      serNum: record.serNum,
      bannerId: record.bannerId,
      picUrl: record.picUrl,
    });
    setModalTitle('编辑轮播图');
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (bannerId: string) => {
    try {
      await deleteTopBannerPic({ bannerId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理新增/编辑表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);
      
      // 构建提交数据
      const submitData = {
        ...values,
        picUrl: imageUrl || values.picUrl,
      };
      
      if (currentBanner) {
        await updateTopBannerPic(submitData);
      } else {
        await addTopBannerPic(submitData);
      }
      
      message.success(`${currentBanner ? '更新' : '新增'}成功`);
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error(`${currentBanner ? '更新' : '新增'}失败`);
    } finally {
      setConfirmLoading(false);
    }
  };

  // 图片上传前的校验
  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
    }
    
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    
    return isImage && isLt2M;
  };

  // 图片上传配置 - 使用真实接口
  const uploadProps: UploadProps = {
    name: 'file',
    customRequest: async ({ file, onSuccess, onError, onProgress }) => {
      try {
        const response = await uploadMinio(file as File);
        if (response.data?.fileUrl) {
          onSuccess?.(response, new XMLHttpRequest());
        } else {
          onError?.(new Error('上传失败'), new XMLHttpRequest());
        }
      } catch (error) {
        onError?.(error as Error, new XMLHttpRequest());
      }
    },
    showUploadList: false,
    beforeUpload,
    onChange(info) {
      if (info.file.status === 'uploading') {
        return;
      }
      
      if (info.file.status === 'done') {
        // 根据实际接口返回格式调整
        const url = info.file.response?.data?.fileUrl || "";
        if (url) {
          setImageUrl(url);
          form.setFieldsValue({ picUrl: url });
          message.success('图片上传成功');
        } else {
          message.error('获取图片URL失败');
        }
      } else if (info.file.status === 'error') {
        message.error('图片上传失败');
      }
    },
  };

  // 重置表单
  const resetForm = () => {
    form.resetFields();
    setImageUrl('');
    setCurrentBanner(null);
  };

  // 打开新增模态框
  const handleAdd = () => {
    resetForm();
    setModalTitle('新增轮播图');
    setModalVisible(true);
  };

  return (
    <PageContainer>
      <ProTable<BannerItem>
        headerTitle="轮播图列表"
        actionRef={actionRef}
        rowKey="bannerId"
        search={false}
        toolBarRender={() => [
          <Button 
            key="add" 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增轮播图
          </Button>,
        ]}
        request={async (params) => {
          // 构建请求参数
          const requestParams = {
            pageSize: params.pageSize,
            pageIndex: params.current,
            param: {},
          };
          
          try {
            const result = await qryTopBannerListPage(requestParams);
            return {
              data: result.list,
              success: true,
              total: result.total,
            };
          } catch (error) {
            message.error('获取轮播图列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          showQuickJumper: true,
        }}
      />

      {/* 新增/编辑模态框 */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisible(false)}
        afterClose={resetForm}
      >
        <Form
          form={form}
          layout="vertical"
        >
          {currentBanner && (
            <Form.Item
              name="bannerId"
              label="轮播图ID"
            >
              <Input disabled />
            </Form.Item>
          )}
          
          <Form.Item
            name="serNum"
            label="排序序号"
            rules={[{ required: true, message: '请输入排序序号' }]}
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="picUrl"
            label="图片URL"
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <Input 
              placeholder="图片URL将在上传后自动填入" 
              disabled 
              style={{ color: 'rgba(0, 0, 0, 0.65)' }}
            />
          </Form.Item>
          
          <Form.Item label="上传图片">
            <Upload {...uploadProps}>
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'center' 
              }}>
                {imageUrl ? (
                  <img 
                    src={imageUrl} 
                    alt="轮播图" 
                    style={{ width: '100%', maxHeight: '200px', marginBottom: '8px' }} 
                  />
                ) : null}
                <Button icon={<PlusOutlined />}>点击上传</Button>
              </div>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default BannerPage;